package com.tools.module.base.service.impl;

import com.tools.common.model.Result;
import com.tools.common.util.Constant;
import com.tools.common.util.UploadFileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service
public class UploadFileService {
    @Value("${path.rootUrl}")
    String rootUrl;
    /**
     * 文件上传
     *
     * @param
     * @return
     * @throws Exception
     */
    public Result fileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        Map<String, Object> data = new HashMap<String, Object>();
        //这里是拿到文件名
        String fileName = file.getOriginalFilename();
        //这里是拿到文件后缀
        String suffix =fileName.substring(fileName.lastIndexOf("."));
        System.out.println(suffix);
        //获取文件上传路径
        String uploadPath = Constant.FilePath.getUploadPath(suffix);
        if (StringUtils.isNotBlank(uploadPath)){
            //拼接文件配置的上传地址
            String targetDir =Constant.UPLOAD_PATH+uploadPath;
             //String targetDir ="/Users/haodongjie/IdeaProjects";
            //这里是工具类
            UploadFileUtil.uploadFile(file.getBytes(), targetDir, fileName);
            data.put("fileUrl",rootUrl+ uploadPath + File.separator + fileName);
           // data.put("fileUrl",targetDir + File.separator + fileName);
            data.put("fileType",Constant.FilePath.getUploadIndex(suffix));
            System.out.println(" file ==>" + fileName + "==>upload to " + rootUrl+targetDir +"/"+fileName);
        }else {
            System.out.println("此文件格式不支持上传！");
            return Result.ok("此文件格式不支持上传！");
        }
        return Result.ok(data);
    }
}
